import csv
import sys
import os

# 获取当前脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))

# 将父目录添加到sys.path中
parent_dir = os.path.dirname(script_dir)
sys.path.append(os.path.join(parent_dir, 'my_package'))
from my_package.china_address_mapping import province_dict, address_dict

# 定义 CSV 文件的路径和名称
csv_file = os.path.join(script_dir, 'address.csv')

try:
    # 打开 CSV 文件进行写入操作
    with open(csv_file, 'w', newline='', encoding='utf-8') as file:
        # 写入注释行
        file.write('# address.csv\n')
        writer = csv.writer(file)
        # 写入 CSV 文件的表头
        writer.writerow(['编码', '名称'])
        # 遍历字典，将键值对写入 CSV 文件
        for code, name in address_dict.items():
            writer.writerow([code, name])

    print(f"数据已成功写入 {csv_file} 文件。")
except Exception as e:
    print(f"写入文件时出现错误: {e}")


# 定义 CSV 文件的路径和名称
csv_file = os.path.join(script_dir, 'province.csv')

try:
    # 打开 CSV 文件进行写入操作
    with open(csv_file, 'w', newline='', encoding='utf-8') as file:
        # 写入注释行
        file.write('# province.csv\n')
        writer = csv.writer(file)
        # 写入 CSV 文件的表头
        writer.writerow(['编码', '名称'])
        # 遍历字典，将键值对写入 CSV 文件
        for code, name in province_dict.items():
            writer.writerow([code, name])

    print(f"数据已成功写入 {csv_file} 文件。")
except Exception as e:
    print(f"写入文件时出现错误: {e}")